package edu.gu.derp.beans.login;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import edu.gu.derp.model.Account;
import edu.gu.derp.model.Database;
import edu.gu.derp.model.DummyController;
import edu.gu.derp.model.IController;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;


/**
 *
 * @author jensc
 */

@ManagedBean(name="LoginControllerBean")
@RequestScoped
public class LoginControllerBean{
    private final String ERROR_INCORRECT_PASSWORD = "Password is incorrect.";
    private final String ERROR_INCORRECT_USER = "User does not exist.";
    
    @ManagedProperty(value="#{LoginBackingBean.name}")
    private String name;
    
    @ManagedProperty(value="#{LoginBackingBean.password}")
    private String password;

    private IController controller = Database.getController();

    public void login() {
        FacesContext context = FacesContext.getCurrentInstance();
        
        if (controller.accountExists(name)) {
            Account account = (Account) controller.getAccount(name);
            if (password.equals(account.getPassword())) {
                context.getExternalContext().getSessionMap().put("account", account);
            } else {
                FacesMessage message = new FacesMessage();
                message.setSummary(ERROR_INCORRECT_PASSWORD);
                message.setDetail(ERROR_INCORRECT_PASSWORD);
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                context.addMessage("formLogin:password", message);
            }
        } else {
            FacesMessage message = new FacesMessage();
            message.setSummary(ERROR_INCORRECT_USER);
            message.setDetail(ERROR_INCORRECT_USER);
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            context.addMessage("formLogin:name", message);
        }
    }
    
    public LoginControllerBean(){
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
   
}
